package lib.bone.admin.controller.system;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.access.module.post.NepuPostService;
import lib.bone.access.module.post.domain.NepuPost;
import lib.bone.access.module.post.domain.dto.PostAddDTO;
import lib.bone.access.module.post.domain.dto.PostQueryDTO;
import lib.bone.access.module.userpost.domain.dto.PostBindDTO;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.exception.BusinessException;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("nepu")
@Api(tags = "岗位管理")
public class  NepuPostController {
    @Autowired
    NepuPostService service;


//    @Autowired
//    NepuUserPostService nepuUserPostService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    NepuPostService postService;

    /* 获取用户岗位信息内部类 */
    public NepuPost getUserPost(Long userId,Boolean allowNull){
        Optional<SysUser> userOp = sysUserService.getById(userId);
        if (!userOp.isPresent()) throw new BusinessException(ResponseCodeConst.NOT_FOUND,"不存在对应用户");
        return null;
    }


//    @WebLog(module = "bone-system")
    @PostMapping("post")
    @ApiOperation(value = "新增岗位")
    public ResponseDTO newPost(@RequestBody PostAddDTO dto){
        NepuPost post = new NepuPost();
        BeanUtil.copyProperties(dto,post, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Boolean isExist = service.isSame(post);
        if (isExist)
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"存在相同数据");
        return ResponseDTO.succData(service.saveOne(post));
    }

    @GetMapping("post/{postId}")
    @ApiOperation(value = "查询岗位")
    public ResponseDTO getPost(@PathVariable("postId") String postId){
        Optional<NepuPost> postOp = service.getById(postId);
        if (!postOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        return ResponseDTO.succData(postOp.get());
    }

    @WebLog(module = "bone-system",operate = MethodTypeConst.DELETE)
    @DeleteMapping("post/{postId}")
    @ApiOperation(value = "删除岗位")
    public ResponseDTO deletePost(@PathVariable("postId") String postId){
        return service.deleteById(postId);
    }

    @GetMapping("post")
    @ApiOperation(value = "查询岗位列表")
    public ResponseDTO getPost(PostQueryDTO dto){
        Sort sort;
        if(dto.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, dto.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, dto.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(dto.getPageNum() - 1 , dto.getPageSize(), sort);

        NepuPost post = new NepuPost();
        BeanUtil.copyProperties(dto,post, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<NepuPost> example = Example.of(post);

        //return nepuPaperDictService.getAll(pageable,example);
        return ResponseDTO.succData(service.getAll(pageable,example));
    }

    /**
     * 岗位绑定
     */
    @WebLog(module = "bone-system",operate = MethodTypeConst.UPDATE)
    @PostMapping("post/bind")
    @ApiOperation(value = "岗位信息绑定",notes = "登录用户才可操作该接口")
    public ResponseDTO postBind(@RequestBody PostBindDTO dto){
        Long userId = StpUtil.getLoginIdAsLong();
        String postId = dto.getPostId();
        Optional<NepuPost> postOp = service.getById(postId);
        if (!postOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"没有ID:["+postId+"]对应岗位信息");
        }
        /* 查询用户信息 */
        Optional<SysUser> userOp = sysUserService.getById(userId);
        if (!userOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到对应用户");

        SysUser user = userOp.get();

//        Optional<NepuUserPost> nepuUserPostOp = nepuUserPostService.findByUserId(userId);
//        NepuUserPost userPost = new NepuUserPost();
//        if (nepuUserPostOp.isPresent()){
//          userPost = nepuUserPostOp.get();
//        }
//        userPost.setPostId(postId);
//        userPost.setUserId(userId);
//        Optional<SysUser> sysUserOp = sysUserService.getById(userId);
//        if (!sysUserOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        SysUser user = sysUserOp.get();
        user.setPostId(postId);
        sysUserService.updateOne(user);
        return ResponseDTO.succMsg("岗位更新成功");
    }
    /**
     * 获取post信息
     */
    @GetMapping("post/profile")
    @ApiOperation(value = "获取个人岗位信息")
    public ResponseDTO<NepuPost> getPostProfile(){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<SysUser> userOp = sysUserService.getById(userId);
        if (!userOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到对应用户");

        SysUser user = userOp.get();
        String postId = user.getPostId();
        Optional<NepuPost> postOp = postService.getById(postId);
        return postOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND));
//        Optional<NepuUserPost> userPostOp = nepuUserPostService.findByUserId(userId);
//        if (!userPostOp.isPresent()){
//         //   return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//            return ResponseDTO.succData(null);
//        }
//        NepuUserPost nepuUserPost = userPostOp.get();
//        Optional<NepuPost> postOp = service.getById(nepuUserPost.getPostId());
//        // return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        return postOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.succData(null));
    }
}
